package com.tanhua.sso.service;

import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.tanhua.common.mapper.UserInfoMapper;
import com.tanhua.common.pojo.User;
import com.tanhua.common.pojo.UserInfo;
import com.tanhua.common.enums.SexEnum;
import com.tanhua.common.service.PicUploadService;
import com.tanhua.common.vo.PicUploadResult;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import java.io.IOException;
import java.util.Map;

/**
 * @Author 王加鑫
 * @Date 2021/09/01 21:15
 * @Since JDK 1.8
 */
@Service
@Slf4j
public class UserInfoService {

    @Autowired
    private UserService userService;

    @Autowired
    private UserInfoMapper userInfoMapper;

    @Autowired
    private FaceEngineService engineService;

    @Autowired
    private PicUploadService picUploadService;


    /**
     * 保存用户个人资料(头像除外)
     * @param map
     * @param token
     * @return
     */

    public Boolean saveUserInfo(Map<String, String> map, String token) {
        //校验token
        User user = userService.queryUserByToken(token);
        if(null == user){
            //根据token查询不出数据，说明用户不合法
            return false;
        }

        //走到此处说明用户合法，完善用户个人信息资料
        UserInfo userInfo = new UserInfo();
        userInfo.setUserId(user.getId());
        userInfo.setSex(StringUtils.equalsIgnoreCase(map.get("gender"), "man") ? SexEnum.MAN : SexEnum.WOMAN);
        userInfo.setNickName(map.get("nickname"));
        userInfo.setBirthday(map.get("birthday"));
        userInfo.setCity(map.get("city"));
        return this.userInfoMapper.insert(userInfo) == 1;
    }

    /**
     * 上传用户头像
     * @param file
     * @param token
     * @return
     */
    public Boolean saveUserLogo(MultipartFile file, String token) {
        User user = userService.queryUserByToken(token);
        if(null == user){
            //用户无效，返回false
            return false;
        }
        try {
            boolean flag = this.engineService.checkIsPortrait(file.getBytes());
            if(!flag){
                return false;
            }
        } catch (IOException e) {
            log.error("上传头像失败",e);
        }

        //图片上传到阿里云oss
        PicUploadResult result = this.picUploadService.upload(file);
        if(StringUtils.isEmpty(result.getName())){
            //上传失败
            return false;
        }

        //把头像保存到用户信息表中
        UserInfo userInfo = new UserInfo();
        userInfo.setLogo(result.getName());
        UpdateWrapper<UserInfo> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("user_id",user.getId());
        return userInfoMapper.update(userInfo,updateWrapper) == 1;
    }
}
